package com.example.servlet;

import com.example.dao.QuestionDAO;
import com.example.model.Question;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/post")
public class PostServlet extends HttpServlet {
    private QuestionDAO questionDAO;

    @Override
    public void init() throws ServletException {
        try {
            questionDAO = new QuestionDAO();
        } catch (Exception e) {
            throw new ServletException("初始化问题 DAO 失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String title = request.getParameter("title");
        String content = request.getParameter("content");

        if (title == null || title.trim().isEmpty() || content == null || content.trim().isEmpty()) {
            request.setAttribute("error", "标题和内容不能为空");
            request.getRequestDispatcher("postForm.jsp").forward(request, response);
            return;
        }

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        try {
            Question newQuestion = new Question();
            newQuestion.setTitle(title);
            newQuestion.setContent(content);
            newQuestion.setUserId(((com.example.model.User) session.getAttribute("user")).getId());

            questionDAO.addQuestion(newQuestion);
            response.sendRedirect("index.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误");
            request.getRequestDispatcher("postForm.jsp").forward(request, response);
        }
    }
}